<?php

require_once (fvSite::$fvConfig->get("path.entity") . 'menu.class.php') ;

class MenuManager extends fvRootManager {
	
	protected function __construct () {
	    $objectClassName = substr(__CLASS__, 0, -7);
	    
	    // Tweak for ManagerManager Class ;)
	    if ($objectClassName == "") $objectClassName = "Manager";
	    
	    $this->rootObj = new $objectClassName();
	}
	
    static function getInstance()
    {
        static $instance; 
        
        $className = __CLASS__;
        
        if (!isset($instance)) {
            $instance = new $className();
        }  
        return $instance;
    }

    function htmlSelect ($field, $empty = "", $where = null, $order = null, $limit = null, $args = array()) {
        $result = array('0' => 'корневой пункт меню');
        
        if (!is_array($args)) $args = array(($args)?$args:'');
        
        $result = $result + parent::htmlSelect($field, $empty, $where, $order, $limit, $args);
        return $result;
    }
    
    function getMenuTree($where = null, $args = array()) {
        $query = "SELECT q.* FROM " . $this->rootObj->getTableName() . " q 
left join " . $this->rootObj->getTableName() . " q_p on q_p.id = q.parent_id";
        if (!empty($where)) $query .= "\nWHERE (" . $where . ")";
        $query .= "\norder by IF (q.parent_id = 0, (q.menu_order + 1)*100000, (q_p.menu_order + 1)*100000 + (q.menu_order + 1))";
        
        $res = fvSite::$DB->query($query, $params);

        $result = array();
        
        if (!DB::isError($res)) {
            while ($row = $res->fetchRow()) {
                $o = clone $this->rootObj;
                $o->hydrate($row);
                
                $result[] = $o;
            }
        }
        
        return $result;
    }
}